<!--
 * @Author: wuzhen
 * @Date: 2019-12-21 14:36:03
 * @LastEditors  : wuzhen
 * @LastEditTime : 2020-01-08 19:26:39
 * @Description: 管理员管理
 -->
<template>
  <Card style="width:100%" dis-hover>
    <!-- 搜索表头/表头按钮 -->
    <search-table :search-props="searchProps" :search-buttons="searchButtons" @handle-click="handleClick" @handle-filter="handleFilter" />
    <wz-table ref="table" :search-api="searchApi" :columns="columns" :handle-btn="handleBtn" @handle-click="handleClick" />
    <!-- 用户添加、编辑 -->
    <Modal v-model="editDrawer" :title="editTitle" @on-cancel="editDrawer = false" width="500">
      <wz-form v-if="editDrawer && !roleDrawer" ref="form" :label-width="100" :form-obj="formObj" :form-props="formProps" />
      <wz-form v-if="editDrawer && roleDrawer" ref="form" :label-width="10" :form-obj="formObj" :form-props="formPropsRole">
        <template v-slot:role="slotProps">
          <FormItem :prop="slotProps.item.key">
            <Transfer :data="roleData" :target-keys="targetKeys" :titles="['未选角色', '已选角色']" @on-change="changeRole"></Transfer>
          </FormItem>
        </template>
      </wz-form>
      <div slot="footer">
        <Button type="text" @click="editDrawer = false">取消</Button>
        <Button type="primary" @click="onSubmit">确定</Button>
      </div>
    </Modal>
  </Card>
</template>
<script>
import {
  getAdminList,
  addAdmin,
  editAdmin,
  getRoleList,
  editAdminRole,
  resetAdminPassword
} from "@/request/api";
import index from "./mixins";
import form from "./mixins/form";
export default {
  mixins: [index, form],
  data() {
    return {
      searchApi: getAdminList,
      apiParams: {
        flipper: {
          offset: 0,
          limit: 15,
          sort: "memberid DESC"
        },
        bean: {
          membername: "",
          account: ""
        }
      },
      editDrawer: false,
      roleDrawer: false,
      editTitle: "添加",
      formObj: {},
      roleData: [],
      targetKeys: []
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    // 获取菜单数据
    async getData() {
      try {
        // 获取角色数据
        const res = await getRoleList();
        this.roleData = res.result.rows.map(v => {
          return {
            key: v.roleid,
            label: v.rolename
          };
        });
        await this.$refs["table"].getData(this.apiParams);
      } catch (error) {
        throw error;
      }
    },
    // 修改角色
    changeRole(newTargetKeys) {
      this.targetKeys = newTargetKeys;
    },
    // 查询
    handleFilter(params) {
      this.apiParams["bean"] = params;
      this.getData();
    },
    handleClick(type, row) {
      this.formObj = row || {};
      this.type = type;
      this.roleDrawer = false;
      this.editDrawer = true;
      switch (type) {
        case "add":
          this.editTitle = "添加";
          break;
        case "edit":
          this.editTitle = "编辑";
          break;
        case "role":
          this.editTitle = "角色管理";
          this.roleDrawer = true;
          this.targetKeys = row.roleids;
          break;
        case "reset": // 重置密码
          this.editDrawer = false;
          this.$Modal.warning({
            title: "友情提示",
            content: "确定要重置密码？",
            closable: true,
            onOk: () => {
              this.onReset();
            }
          });
          break;
        default:
          break;
      }
    },
    // 重置密码
    async onReset() {
      try {
        const res = await resetAdminPassword({
          userid: this.formObj["memberid"]
        });
        if (res.code === 200) {
          this.$Notice.success({
            title: "重置成功",
            desc: `新密码：${res.attach.pwd}`,
            duration: 0
          });
        } else {
          this.$Message.error(res.retinfo);
        }
      } catch (error) {
        throw error;
      }
    },

    // 确定
    async onSubmit() {
      try {
        const validate = await this.$refs.form.validate();
        if (validate.valid) {
          let res;
          if (this.type === "add") {
            res = await addAdmin({
              bean: JSON.stringify({
                ...validate.formData
              })
            });
          } else if (this.type === "edit") {
            res = await editAdmin({
              bean: JSON.stringify({
                ...validate.formData
              })
            });
          } else {
            const delroleids = this.$_.difference(
              this.formObj["roleids"],
              this.targetKeys
            );
            const bean = this.$_.difference(
              this.targetKeys,
              this.formObj["roleids"]
            );
            const arrayData = bean.map(v => {
              return {
                memberid: this.formObj["memberid"],
                roleid: v
              };
            });
            res = await editAdminRole({
              delmemberid: this.formObj["memberid"],
              delroleids: JSON.stringify(delroleids),
              bean: JSON.stringify(arrayData)
            });
          }

          if (res.code === 200) {
            this.$Message.success("操作成功");
            this.editDrawer = false;
            if (this.type === "add") {
              this.$Notice.success({
                title: "添加成功",
                render: h => {
                  return h("div", [
                    h("p", `账号：${validate.formData["account"]}`),
                    h("p", `密码：${res.attach.pwd}`)
                  ]);
                },
                duration: 0
              });
            }
            this.getData();
          } else {
            this.$Message.error("操作失败");
          }
        }
      } catch (error) {
        throw error;
      }
    }
  }
};
</script>
<style lang="less" scoped></style>
